package com.jin.flashsaled.utils;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import org.springframework.http.ResponseCookie;

import java.time.Duration;
import java.util.Arrays;
import java.util.Optional;

/**
 * Cookie 快速生成 / 读取 / 删除 工具类
 * 支持“传统 Cookie”与“Spring ResponseCookie”两种写法
 */
public final class CookieUtil {

    private CookieUtil() {}

    /* ==========================
           写 Cookie（传统）
       ========================== */

    /**
     * 创建并写入浏览器
     * @param name     名称
     * @param value    值（建议 Base64/URL 编码敏感字符）
     * @param maxAge   存活秒数；null 表示默认浏览器会话
     * @param httpOnly 是否禁止 JS 读取
     * @param secure   是否仅 HTTPS 传输
     * @param domain   作用域；null 表示当前域
     * @param path     路径；null 默认 "/"
     */
    public static void addCookie(HttpServletResponse resp,
                                 String name,
                                 String value,
                                 Integer maxAge,
                                 boolean httpOnly,
                                 boolean secure,
                                 String domain,
                                 String path) {
        Cookie c = new Cookie(name, value);
        if (maxAge != null) c.setMaxAge(maxAge);
        c.setHttpOnly(httpOnly);
        c.setSecure(secure);
        if (domain != null) c.setDomain(domain);
        c.setPath(path == null ? "/" : path);
        resp.addCookie(c);
    }

    /* 最简重载 */
    public static void addCookie(HttpServletResponse resp, String name, String value, int maxAge) {
        addCookie(resp, name, value, maxAge, true, false, null, "/");
    }

    /* ==========================
           写 Cookie（Spring 风格，SameSite 支持）
       ========================== */
    public static void addCookieSameSite(HttpServletResponse resp,
                                         String name,
                                         String value,
                                         Duration maxAge,
                                         boolean httpOnly,
                                         boolean secure,
                                         String domain,
                                         String path,
                                         String sameSite) {
        ResponseCookie rc = ResponseCookie.from(name, value)
                .httpOnly(httpOnly)
                .secure(secure)
                .domain(domain)
                .path(path == null ? "/" : path)
                .maxAge(maxAge)
                .sameSite(sameSite)          // Strict / Lax / None
                .build();
        resp.addHeader("Set-Cookie", rc.toString());
    }

    /* 最简重载 */
    public static void addCookieSameSite(HttpServletResponse resp, String name, String value, int maxAge) {
        addCookieSameSite(resp, name, value, Duration.ofSeconds(maxAge),
                true, false, null, "/", "Lax");
    }

    /* ==========================
           读 Cookie
       ========================== */
    public static Optional<String> readCookie(HttpServletRequest req, String name) {
        if (req.getCookies() == null) return Optional.empty();
        return Arrays.stream(req.getCookies())
                .filter(c -> name.equals(c.getName()))
                .map(Cookie::getValue)
                .findFirst();
    }

    /* ==========================
           删 Cookie
       ========================== */
    public static void deleteCookie(HttpServletResponse resp,
                                    String name,
                                    String domain,
                                    String path) {
        addCookie(resp, name, null, 0, true, false, domain, path == null ? "/" : path);
    }

    public static void deleteCookie(HttpServletResponse resp, String name) {
        deleteCookie(resp, name, null, "/");
    }


}
